import { message } from "antd"
import { useEffect, useState } from "react"

const usePagingList = ({
  apis,
  defaultQueryValues = {},
  isAutoQuery = true,
  getResData = (res) => {
    return res.data
  }
}) => {

  const [listData, setListData] = useState([])
  const [queryValues, setQueryValues] = useState(defaultQueryValues)
  const [loading, setLoading] = useState(false)
  const [selectedRowKeys, setSelectedRowKeys] = useState([])

  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys) => {
      setSelectedRowKeys(selectedRowKeys)
    },
  }

  const doQueryList = async () => {
    if (!loading) {
      setLoading(true)
      try {
        const res = await apis.queryList(queryValues)
        setListData(getResData(res))
      } catch (error) {
        message.error('查询失败')
      }
      setLoading(false)
    }
  }

  const changeQueryValues = (newValues) => {
    setQueryValues((oldValues) => {
      return {
        ...oldValues,
        ...newValues
      }
    })
  }

  useEffect(() => {
    if (isAutoQuery) {
      doQueryList()
    }
  }, [queryValues])

  return {
    listData,
    loading,
    queryValues,
    doQueryList,
    changeQueryValues,
    selectedRowKeys,
    setSelectedRowKeys,
    rowSelection
  }

}

export default usePagingList